import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HeroService } from '../../../services/hero.service';
import { StorageService } from '../../../services/storage.service';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';

@Component({
  selector: 'app-printer',
  templateUrl: './printer.component.html',
  styleUrls: ['./printer.component.css']
})
export class PrinterComponent implements OnInit {

  isLoading = false;
  isVisible = false;
  isSignVisible = false;
  removeVisible = false;
  loading = true;
  btn_loading = false;
  public removeSignCode: boolean = true;
  public clearSignCode: boolean = true;
  public name: string = '';
  public brandName: string = '';
  public typeCode: string = '';
  public companyName: string = '';
  public isSigned: string = '';
  public status: string = '';
  public isAuto: string = '';
  public printerlist: Array<any> = [];
  public childValue: Array<any> = [];
  public disablePrinterlist: Array<any> = [];
  public disablePrinterName: string;
  public userinfo: string;
  public printerSet: string;
  public PageIndex: number = 1;
  public PageSize: number = 10;
  public PageTotal: number;
  public uploadUrl: string;
  public timer:any;
  allChecked = false;
  indeterminate = false;
  constructor(private heroService: HeroService,
              private storageService: StorageService,
              private http: HttpClient,
              private message: NzMessageService,
              private modalService: NzModalService) { }

  ngOnInit() {
    this.uploadUrl = host + "/main/merchantPrinter/excelImport";
    this.getPrintlist();
    // 定时（5s）刷新设备页面打印数据
    // this.timer = setInterval( () => {
      // console.log(1)
      // this.getPrintlist()
    // },5000)
  }
  // ngOnDestroy() {
  //   clearInterval(this.timer)
  // }

  //获取打印机列表数据
  getPrintlist() {
    this.btn_loading = true;
    let url = host + "/main/merchantPrinter/list";
    let model = "nameLike=" + this.name + "&brandNameLike=" + this.brandName + "&typeCodeLike=" + this.typeCode + "&companyNameVague=" + this.companyName + "&isSigned=" + this.isSigned + "&isAuto=" + this.isAuto + "&status=" + this.status + "&page=" + this.PageIndex + "&pageSize=" + this.PageSize;
    this.heroService.post(url, model).then(result => {
      this.btn_loading = false;
      if (result.code == 0) {
        this.printerlist = result.data.pageBean.result;
        this.printerlist.forEach(data => {
          data.checked = false;
        });
        this.userinfo = result.data.connectUser;
        this.printerSet = result.data.printerSet;
        this.PageIndex = result.data.pageBean.curPage;
        this.PageTotal = result.data.pageBean.totalRow;
        this.loading = false;
      } else {
        this.modalService.error({
          nzTitle: '提示',
          nzContent: result.msg
        });
      }
    })
  }

  delete(value) {
    let url = host + "/main/merchantPrinter/del";
    let model = 'id=' + value;
    this.heroService.post(url, model).then(result => {
      if (result.code == 0) {
        this.message.success('删除成功！');
        this.getPrintlist();
      } else {
        this.message.success(result.msg);
      }
    })
  }
  // 获取上传Excel返回信息
  logoChange(info: any): void {
    this.isLoading = true;
    if (info.type == "success") {
      this.isLoading = false;
      if (info.file.response.code == 0) {
        this.message.success('导入成功');
        this.getPrintlist();
      }
      if(info.file.response.data.content_error){
        if (info.file.response.data.content_error.length > 0) {
          console.log(info.file.response.data.content_error);
          let content_error = '';
          for (let i in info.file.response.data.content_error) {
            content_error += info.file.response.data.content_error[i] + '<br>';
          }
          // this.message.info(content_error);
          this.modalService.error({
            nzTitle: '提示',
            nzContent: content_error
          });
        }
      }
      if(info.file.response.data.format_error){
        if (info.file.response.data.format_error.length > 0) {
          console.log(info.file.response.data.format_error);
          let format_error = '';
          for (let i in info.file.response.data.format_error) {
            format_error += info.file.response.data.format_error[i] + '<br>';
          }
          // this.message.info(format_error);
          this.modalService.error({
            nzTitle: '提示',
            nzContent: format_error
          });
        }
      }
    }
    if (info.type == "removed") {
      this.message.warning('删除成功');
    }
    console.log(info);
  }
  //修改状态
  editStatus(id, getStatus) {
    console.log(id);
    let url = host + "/main/merchantPrinter/stopOrStart";
    if (getStatus == 0) {
      var status = 1;
    } else if (getStatus == 1) {
      var status = 0;
    }
    let model = 'id=' + id + '&status=' + status;
    this.heroService.post(url, model).then(result => {
      console.log(result.code);
      if (result.code == 0) {
        this.message.success('修改状态成功！');
        this.getPrintlist();
      } else {
        this.modalService.error({
          nzTitle: '提示',
          nzContent: result.msg
        });
      }
    })
  }

  //解约
  removeSign(id) {
    // this.removeSignCode 禁止连续点击
    if (this.removeSignCode) {
      this.removeSignCode = false;
      let url = host + "/main/merchantPrinter/rescission";
      let model = 'printerId=' + id;
      this.heroService.post(url, model).then(result => {
        this.removeSignCode = true;
        if (result.code == 0) {
          this.message.success('解约打印机成功！');
          this.getPrintlist();
        } else {
          this.modalService.error({
            nzTitle: '提示',
            nzContent: result.msg
          });
          this.getPrintlist();
        }
      })
    }
  }
  //清算
  clearSign(id) {
    // this.clearSignCode 禁止连续点击
    if (this.clearSignCode) {
      this.clearSignCode = false;
      let url = host + "/main/merchantPrinter/clear";
      let model = 'id=' + id;
      this.heroService.post(url, model).then(result => {
        this.clearSignCode = true;
        if (result.code == 0) {
          this.message.success('清算成功！');
          this.getPrintlist();
        } else {
          this.modalService.error({
            nzTitle: '提示',
            nzContent: result.msg
          });
        }
      })
    }
  }

  //分页
  PageIndexChange(event) {
    this.PageIndex = event;
    this.getPrintlist();
  }

  //导出Excel
  exportOut() {
    const token = this.storageService.getItem("token");
    window.location.href = host + "/main/merchantPrinter/excelExport?token=" + token + "&nameLike=" + this.name + "&brandNameLike=" + this.brandName + "&typeCodeLike=" + this.typeCode + "&companyNameVague=" + this.companyName + "&isSigned=" + this.isSigned + "&isAuto=" + this.isAuto + "&status=" + this.status;
  }
  //下载模板
  downLoadFile() {
    window.location.href = 'http://s2m-test.b0.upaiyun.com/zgysaas/excel/打印机导入模板.xlsx';
  }
  //导入Excel
  exportIn(file) {
    console.log(file);
    let url = host + "/user/merchantPrinter/excelImport=";
    this.http.post(url, file, { responseType: 'text' }).subscribe(result => {
      console.log(result);
    })
  }
  //全选
  refreshStatus(): void {
    const allChecked = this.printerlist.every(value => value.checked === true);
    const allUnChecked = this.printerlist.every(value => !value.checked);
    this.allChecked = allChecked;
    this.indeterminate = (!allChecked) && (!allUnChecked);
  }

  checkAll(value: boolean): void {
    this.printerlist.forEach(data => {
      data.checked = value;
    });
    this.refreshStatus();
  }
  //批量预警配置
  bindSetconfig() {
    let checklist = [];
    this.printerlist.forEach(data => {
      if (data.checked) {
        checklist.push(data.id);
      }
    });
    console.log(checklist);
    if (checklist.length > 0) {
      this.childValue = checklist;
      this.isVisible = true;
    } else {
      this.message.warning('请至少选择一个设备！');
    }
  }
  handleCancel() {
    this.isVisible = false;
  }
  //批量签约
  bindSign() {
    let checklist = [];
    this.disablePrinterlist = [];
    this.printerlist.forEach(data => {
      if (data.checked) {
        if (!data.isSigned && data.status == 0) {
          checklist.push(data.id);
        } else {
          data.checked = false;
          this.disablePrinterlist.push(data.name);
        }
      }
    });
    if (this.disablePrinterlist.length > 0) {
      this.allChecked = false;
      this.isSignVisible = false;

      this.disablePrinterName = "：";
      this.disablePrinterlist.forEach(data => {
        this.disablePrinterName += data + ",";
      });
      this.modalService.warning({
        nzTitle: '提示',
        nzContent: "打印机" + this.disablePrinterName + '<br>' + "状态条件不符合，已帮您去掉勾选"
      });
    } else {
      if (checklist.length > 0) {
        this.childValue = checklist;
        this.isSignVisible = true;
      } else {
        this.message.warning('请至少选择一个设备！');
      }
    }
    console.log(checklist);
  }
  signHandleCancel() {
    this.isSignVisible = false;
  }
  confirm(id): void {
    this.modalService.confirm({
      nzTitle: '确定要解约该打印机么',
      nzContent: '<p>合同未到期若强制解约会自动结算账单</p>',
      nzOnOk: () => this.removeSign(id)
    });
  }
  confirm2(id): void {
    this.modalService.confirm({
      nzTitle: '确定要清算吗',
      nzOnOk: () => this.clearSign(id)
    });
  }
  //子组件向父组件传值
  showInfo($event) {
    this.isVisible = $event.isVisible;
  }
  showSignInfo($event) {
    this.isSignVisible = $event.isSignVisible;
    this.getPrintlist();
  }
}
